package com.alibaba.dubbo.demo.impl;

import com.alibaba.dubbo.demo.RcmdService;
import redis.clients.jedis.Jedis;

import java.util.*;
import java.util.Map.Entry;

public class RcmdServiceImpl implements RcmdService {
    @Override
    public List<String> getRcmdList(String uid) {
       // 获得数据库连接
        Jedis jedis = new Jedis("192.168.206.129", 6379);
        jedis.select(2);
        // 从用户历史下载表来获取最近下载
        String downloads = jedis.hget("rcmd_user_history", uid);
        // 关键修改：检查是否为空
        if (downloads == null || downloads.isEmpty()) {
            return Collections.emptyList(); // 或根据业务需求返回默认值
        }
        String[] downloadList = downloads.split(",");

        // 获取所有appID列表
        Set<String> appList = jedis.hkeys("rcmd_item_list");

        // 存储总的特征分值
        Map<String, Double> scoresMap = new HashMap<String, Double>();

        // 分别计算所有应用的总权重
        for (String appId : appList) {
        	if(Arrays.asList(downloadList).contains(appId)) {
        		continue;
        	}
            // 计算关联权重
            double relativeFeatureScore = getRelativeFeatureScore(appId, downloadList, jedis);
            updateScoresMap(scoresMap, appId, relativeFeatureScore);
            // 计算基本权重
            double basicFeatureScore = getBasicFeatureScore(appId, jedis);
            updateScoresMap(scoresMap, appId, basicFeatureScore);
        }

        //这里将map.entrySet()转换成list
        List<Map.Entry<String, Double>> list = new ArrayList<>(scoresMap.entrySet());
        //然后通过比较器来实现排序
        Collections.sort(list, new Comparator<Map.Entry<String, Double>>() {
            //降序排序
            public int compare(Map.Entry<String, Double> entry1,
                               Map.Entry<String, Double> entry2) {
                return -entry1.getValue().compareTo(entry2.getValue());
            }
        });
        // 打印分值
        for (Map.Entry<String, Double> mapping : list) {
            System.out.println(mapping.getKey() + ":" + mapping.getValue());
        }

        // 取前10个appID返回
        List<String> result = new ArrayList<>();
        int count = 0;
        for (Map.Entry<String, Double> mapping : list) {
            count++;
            result.add(mapping.getKey());
            if(count==10){
                break;
            }
        }

        jedis.close();
        return result;
    }

    private void updateScoresMap(Map<String, Double> scoresMap, String appName, double score) {
        if (scoresMap.get(appName) == null) {
        	scoresMap.put(appName, score);
        } else {
            scoresMap.put(appName, scoresMap.get(appName) + score);
        }
    }

    private double getRelativeFeatureScore(String appId, String[] downloadList, Jedis jedis) {
        double score = 0.0;
        for (String downloadAppId : downloadList) {
            // 构建特征名（根据实际数据格式调整）
            String feature1 = "User.Item*Item," + appId + "*" + downloadAppId;
            String feature2 = "User.Item*Item," + downloadAppId + "*" + appId;

            // 获取并累加特征分数
            String score1 = jedis.hget("rcmd_features_score", feature1);
            if (score1 != null) {
                score += Double.parseDouble(score1);
            }

            String score2 = jedis.hget("rcmd_features_score", feature2);
            if (score2 != null) {
                score += Double.parseDouble(score2);
            }
        }

        return score;
    }

    private double getBasicFeatureScore(String appId, Jedis jedis) {
        // 存储基本特征分值
        double basicScore = 0.0;

        // 从商品词表取基本特征
        /*
            Item.id@146 软件ID
            Item.name@183   名字
            Item.author@zhouming    作者
            Item.sversion@1.3.2 版本号
            Item.ischarge@1 是否收费
            Item.dgner@husheng  设计者
            Item.font@Consolos  字体
            Item.icount@4   图片数量
            Item.icount_dscrt@4
            Item.stars@5    星级
            Item.price  价格
            Item.fsize@6  文件大小
            Item.fsize_dscrt@6
            Item.comNum@0   评论数量
            Item.comNum_dscrt@0
            Item.screen@FHD 屏幕类型
            Item.downNum@200  
            Item.downNum_dscrt@200	下载数
         */
        String[] basicFeatureNames = {"Item.id", "Item.name", "Item.author", "Item.sversion", "Item.ischarge"
                , "Item.dgner", "Item.font", "Item.icount", "Item.icount_dscrt", "Item.stars", "Item.price"
                , "Item.fsize", "Item.fsize_dscrt", "Item.comNum", "Item.comNum_dscrt", "Item.screen", "Item.downNum"
                , "Item.downNum_dscrt"};
        String rcmd_item_list = jedis.hget("rcmd_item_list", appId);
        String[] basicFeatures = rcmd_item_list.split("\t");

// 关键修改：添加数组长度检查
        int featureCount = Math.min(basicFeatureNames.length, basicFeatures.length);
        for (int i = 0; i < featureCount; i++) {
            String rcmd_features_score = jedis.hget("rcmd_features_score", basicFeatureNames[i] + "," + basicFeatures[i]);
            if (rcmd_features_score != null) {
                basicScore += Double.valueOf(rcmd_features_score);
            }
        }

        return basicScore;
    }
}
